package com.ttx.algorithm.leetcode.usual;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TimFruit
 * @date 19-10-4 下午2:48
 */
public class P001TwoSum {

    public int[] twoSum(int[] nums, int target) {


        HashMap<Integer, Integer> numIndexMap=new HashMap<Integer, Integer>();// <num, index>
        HashMap<Integer, Integer> secondNumIndexMap=new HashMap<Integer, Integer>();// <num, index> num存在重复时, 保存第二个num

        for(int i=0, s=nums.length; i<s; i++){
            if(!numIndexMap.containsKey(nums[i])){
                numIndexMap.put(nums[i], i);
                continue;
            }
            if(!secondNumIndexMap.containsKey(nums[i])){
                secondNumIndexMap.put(nums[i],i);
                continue;
            }
            // 第3个之后的重复值舍弃
            System.out.println("舍弃多余的重复值"+nums[i]);

        }

        int[] results=new int[2];

        Integer num=null;
        Integer secNum=null;
        for(Map.Entry<Integer, Integer> entry: numIndexMap.entrySet()){
            num=entry.getKey();
            if(!numIndexMap.containsKey(target-num)){
                continue;
            }

            results[0]=entry.getValue();
            secNum=target-num;
            if(num.intValue()!=secNum){
                results[1]=numIndexMap.get(secNum);
            }else {
                results[1]=secondNumIndexMap.get(secNum);
            }

            break;
        }

        return results;
    }



    public int[] twoSum2(int[] nums, int target) {


        HashMap<Integer, Integer> numIndexMap=new HashMap<Integer, Integer>();// <num, index>

        int secNum;
        for(int i=0;i<nums.length;i++){
            secNum=target-nums[i];
            if(numIndexMap.containsKey(secNum)){
                return new int[]{numIndexMap.get(secNum), i};
            }else {
                numIndexMap.put(nums[i], i);
            }
        }
        throw new RuntimeException("no two sum result ");
    }


}
